﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Descripción breve de ComparadorGenerico
/// </summary>
public class GridViewGenericComparer<T> : IComparer<T>
{
    private SortDirection sortDirection;
    private string sortExpression;

    public GridViewGenericComparer(string sortExpression, SortDirection sortDirection)
    {
        this.sortExpression = sortExpression;
        this.sortDirection = sortDirection;
    }

    public SortDirection SortDirection
    {
        get { return sortDirection; }
        set { sortDirection = value; }
    }

    public int Compare(T x, T y)
    {
        if (x == null) return 0;
        if (y == null) return 0;
        
        PropertyInfo propertyInfo = typeof(T).GetProperty(sortExpression);
        IComparable obj1 = (IComparable)propertyInfo.GetValue(x, null);
        IComparable obj2 = (IComparable)propertyInfo.GetValue(y, null);

        if (SortDirection == SortDirection.Ascending) return obj1.CompareTo(obj2);
        return obj2.CompareTo(obj1); 
    }
}
